<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="top-navbar">
			<view 
				class="nav-item" 
				:class="{ active: activeTab === 'pending' }" 
				@click="switchTab('pending')">
				待处理
			</view>
			<view 
				class="nav-item" 
				:class="{ active: activeTab === 'completed' }" 
				@click="switchTab('completed')">
				已完成
			</view>
		</view>
		<!-- 内容区域 -->
		<view class="content">
			<!-- 待处理列表 -->
			<view v-if="activeTab === 'pending'" class="order-list">
				<view class="order-item" v-for="(order, index) in pendingOrders" :key="order.id">
					<view class="order-header">
						<text class="order-id">订单号：{{ order.id }}</text>
						<text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
					</view>
					<view class="order-info">
						<text class="customer-name">客户：{{ order.name }}</text>
						<text class="order-time">接单时间：{{ order.createTime }}</text>
						<text class="order-service">服务项目：{{ order.title }}</text>
					</view>
					<view class="order-actions">
						<button class="action-btn primary" @click="processOrder(order)">处理订单</button>
						<button class="action-btn" @click="cancelOrder(order)">取消订单</button>
					</view>
				</view>
			</view>
			<!-- 已完成列表 -->
			<view v-if="activeTab === 'completed'" class="order-list">
				<view class="order-item" v-for="(order, index) in completedOrders" :key="order.id">
					<view class="order-header">
						<text class="order-id">订单号：{{ order.id }}</text>
						<text class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
					</view>
					<view class="order-info">
						<text class="customer-name">客户：{{ order.name }}</text>
						<text class="order-time">接单时间：{{ order.createTime }}</text>
						<text class="order-service">服务项目：{{ order.title }}</text>
					</view>
					<view class="order-actions">
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getWorkOrderList, completeOrder, getCompletedOrders, cancelOrder } from '../../api/workOrder.js'
	
	export default {
		data() {
			return {
				activeTab: 'pending', // 默认选中待处理
				pendingOrders: [],
				completedOrders: [],
				pageNo: 1,
				pageSize: 10
			}
		},
		methods: {
			// 切换顶部导航栏标签
			switchTab(tab) {
				this.activeTab = tab;
				// 切换标签时加载对应数据
				this.loadOrders();
			},
			
			// 加载工单数据
			async loadOrders() {
				// 显示加载提示
				uni.showLoading({
					title: '加载中...'
				});
				
				try {
					// 根据当前标签加载对应的数据列表
					const params = {
						pageNo: this.pageNo,
						pageSize: this.pageSize
					};
					
					// 获取用户信息
					const userInfo = uni.getStorageSync('userInfo');
					if (!userInfo || !userInfo.id) {
						uni.showToast({
							title: '用户未登录',
							icon: 'none'
						});
						return;
					}
					
					// 添加用户ID参数
					params.userId = userInfo.id;
					
					switch(this.activeTab) {
						case 'pending':
						// 待处理工单通过专门的接口获取
						const pendingRes = await getWorkOrderList(params);
						if (pendingRes && pendingRes.code === 0) {
							// 后端直接返回数组，而不是res.data.records结构
							this.pendingOrders = pendingRes.data || [];
						} else {
							this.pendingOrders = [];
							uni.showToast({
								title: '获取待处理工单失败',
								icon: 'none'
							});
						}
						break;
						case 'completed':
						// 已完成工单通过专门的接口获取
						const completedRes = await getCompletedOrders(params);
						if (completedRes && completedRes.code === 0) {
							// 后端直接返回数组，而不是res.data.records结构
							this.completedOrders = completedRes.data || [];
						} else {
							this.completedOrders = [];
							uni.showToast({
								title: '获取已完成工单失败',
								icon: 'none'
							});
						}
						break;
					}
				} catch (error) {
					console.error('加载工单数据异常:', error);
					uni.showToast({
						title: '加载数据异常',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					1: '待处理',
					2: '已抢接',
					3: '已完成',
					4: '已取消'
				};
				return statusMap[status] || '未知状态';
			},
			
			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					1: 'status-pending',
					2: 'status-grabbed',
					3: 'status-completed',
					4: 'status-completed'
				};
				return classMap[status] || '';
			},
			
			// 取消订单
			async cancelOrder(order) {
				uni.showModal({
					title: '取消订单',
					content: '确认取消订单 ' + order.id + ' 吗？',
					success: async (res) => {
						if (res.confirm) {
							// 显示加载提示
							uni.showLoading({
								title: '取消中...'
							});
							
							try {
								// 获取用户信息
								const userInfo = uni.getStorageSync('userInfo');
								if (!userInfo || !userInfo.id) {
									uni.showToast({
										title: '用户未登录',
										icon: 'none'
									});
									return;
								}
								
								// 调用后端接口取消订单
								const res = await cancelOrder({ 
									id: order.id,
									userId: userInfo.id
								});
								
								if (res && res.code === 0) {
									uni.showToast({
										title: '订单取消成功',
										icon: 'success'
									});
									
									// 更新本地订单状态
									order.status = 4;
									
									// 重新加载数据
									this.loadOrders();
								} else {
									uni.showToast({
										title: res.msg || '取消订单失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('取消订单异常:', error);
								uni.showToast({
									title: '取消订单异常',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},
			
			// 处理订单
			async processOrder(order) {
				uni.showModal({
					title: '处理订单',
					content: '确认处理订单 ' + order.id + ' 吗？',
					success: async (res) => {
						if (res.confirm) {
							// 显示加载提示
							uni.showLoading({
								title: '处理中...'
							});
							
							try {
								// 调用后端接口完成工单
								const res = await completeOrder({ id: order.id });
								
								if (res && res.code === 0) {
									uni.showToast({
										title: '订单处理完成',
										icon: 'success'
									});
									
									// 更新本地订单状态
									order.status = 3;
									
									// 重新加载数据
									this.loadOrders();
								} else {
									uni.showToast({
										title: res.msg || '处理订单失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.error('处理订单异常:', error);
								uni.showToast({
									title: '处理订单异常',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			}
		},
		
		// 页面加载时获取数据
		mounted() {
			// 检查是否有新抢到的订单
			const newlyGrabbedOrder = uni.getStorageSync('newlyGrabbedOrder');
			if (newlyGrabbedOrder && this.activeTab === 'pending') {
				// 将新订单添加到待处理订单列表的开头
				this.pendingOrders.unshift(newlyGrabbedOrder);
				// 清除本地存储的新订单数据
				uni.removeStorageSync('newlyGrabbedOrder');
			}
			// 加载完整数据以确保列表是最新的
			this.loadOrders();
		}
	}
</script>

<style>
	.container {
		padding: 0 20rpx;
		padding-top: calc(20rpx + var(--status-bar-height)); /* 为状态栏和导航栏留出空间 */
		padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
		padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
		min-height: 100vh;
		background-color: #f5f5f5;
		box-sizing: border-box;
	}
	
	.top-navbar {
		display: flex;
		background-color: #fff;
		border-radius: 10rpx;
		margin: 20rpx 0;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}
	
	.nav-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #666;
		padding: 20rpx 0;
	}
	
	.nav-item.active {
		color: #007AFF;
		border-bottom: 4rpx solid #007AFF;
	}
	
	/* 内容区域样式 */
	.content {
		/* 移除 overflow-y: auto 避免双重滚动条 */
	}
	
	.order-list {
		padding: 20rpx 0;
	}
	
	.order-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		/* 使用简单边框替代 box-shadow 提升性能 */
		border: 1rpx solid #eee;
		transform: translateZ(0); /* 触发硬件加速 */
		will-change: transform; /* 提示浏览器该元素将要发生变换 */
	}
	
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #eee;
		padding-bottom: 20rpx;
		margin-bottom: 20rpx;
	}
	
	.order-id {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.order-status {
		font-size: 24rpx;
		padding: 6rpx 16rpx;
		border-radius: 30rpx;
	}
	
	.status-pending {
		background-color: #fff3cd;
		color: #856404;
	}
	
	.status-grabbed {
		background-color: #cce5ff;
		color: #004085;
	}
	
	.status-completed {
		background-color: #d4edda;
		color: #155724;
	}
	
	.order-info {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
		margin-bottom: 24rpx;
	}
	
	.customer-name,
	.order-time,
	.order-service {
		font-size: 28rpx;
		color: #333;
	}
	
	.order-actions {
		display: flex;
		gap: 20rpx;
	}
	
	.action-btn {
		flex: 1;
		font-size: 28rpx;
		padding: 16rpx;
		background-color: #f8f9fa;
		border: 1rpx solid #dee2e6;
		border-radius: 10rpx;
		color: #333;
		transform: translateZ(0); /* 触发硬件加速 */
	}
	
	.action-btn.primary {
		background-color: #007AFF;
		color: white;
		border-color: #007AFF;
	}
</style>